import Vue from 'vue'
import qs from 'qs';
import axios from 'axios'
import router from '../../router'
import {Notify} from 'vant';
Vue.use(router);

const Axios = axios.create({
    baseURL: 'http://c.yueshengkj.com/api/',
    timeout: 120000,
    responseType: "json",
    // withCredentials: true, // 跨域是否允许带cookie这些
    headers: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
    }
});
// 在请求或响应被 then 或 catch 处理前拦截它们
Axios.interceptors.request.use((config) => {
    if (localStorage.getItem('token')) {
        config.headers.Authorization = 'Bearer' + localStorage.getItem('token');
    } else { // 登录过验证token
        loginRedirect();
    }
    if (config.method === "post"||config.method==="put") {
        // 序列化
        config.data = qs.stringify(config.data);
    }
    return config;
}, err => {
    // Notify({
    //     message: '数据请求失败',
    //     duration: 1000,
    //     background: '#ff0000'
    // });
    return Promise.reject(err);
});
// 请求后拦截器
Axios.interceptors.response.use(
    result => {
        //对响应数据做些事,根据定义的响应格式和状态码做处理
        if (result.status === 200) {
            return Promise.resolve(result.data);
        } else {
            return Promise.reject(result);
        }
    },
    error => {
        //常见错误操作
        if (error.response) {
            switch (error.response.status) {
                case 400: error.message = '请求错误(400)' ; break;
                case 401:
                    // 这里写清除token的代码
                    error.message = '未授权，请重新登录(401)';

                    router.replace({
                        name: 'login',
                        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
                    });
                    break;
                case 403: error.message = '拒绝访问(403)'; break;
                case 404: error.message = `请求出错(404)`; break;
                case 408: error.message = '请求超时(408)'; break;
                case 500: error.message = '服务器错误(500)'; break;
                case 501: error.message = '服务未实现(501)'; break;
                case 502: error.message = '网络错误(502)'; break;
                case 503: error.message = '服务不可用(503)'; break;
                case 504: error.message = '网络超时(504)'; break;
                case 505: error.message = 'HTTP版本不受支持(505)'; break;
                default: error.message = `连接出错(${err.response.status})!`;

            }
        }
        return Promise.reject(error.response) //请求错误时，直接结束
    });
function loginRedirect () { // 跳转
    router.replace({name: 'login'});
}
export default {
    install: function (Vue, Option) {
        Object.defineProperty(Vue.prototype, "$http", {value: Axios});
    }
};